package com.party.course.controller;

import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hbga.xunpay.Xunpay;
import com.hbga.xunpay.XunpayClient;
import com.hbga.xunpay.exception.XunpayException;
import com.hbga.xunpay.model.ChannelTransparentReqModel;
import com.hbga.xunpay.request.ChannelTransparentRequest;
import com.hbga.xunpay.response.ChannelTransparentResponse;
import com.party.common.core.domain.AjaxResult;
import com.party.common.utils.StringUtils;
import com.party.course.domain.MicroMerchantInfo;
import com.party.course.domain.RealNameInfo;
import com.party.course.service.IRealNameInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 特约商户入网(小微)控制器
 */
@RestController
@RequestMapping("/merchant")
public class MicroMerchantController {




    @Value("${huidiao.domain}")
    private String domainurl;

    @Autowired
    private IRealNameInfoService realNameInfoService;
    @PostMapping("/addRegiserSignMe")
    public AjaxResult addRegiserSignMe(@RequestBody RealNameInfo realNameInfovo) {
        String id = realNameInfovo.getId();
        RealNameInfo realNameInfo = realNameInfoService.getById(id);
        if(realNameInfo!=null){
            // 验参数为必填
            if (StringUtils.isEmpty(realNameInfo.getSignName())) {
                return AjaxResult.error("请填写商户名称");
            }
            if (StringUtils.isEmpty(realNameInfo.getShortName())) {
                return AjaxResult.error("请填写商户简称");
            }
            if (StringUtils.isEmpty(realNameInfo.getLegalName())) {
                return AjaxResult.error("请填写法人姓名");
            }
            if (StringUtils.isEmpty(realNameInfo.getLegalLicenceNo())) {
                return AjaxResult.error("请填写法人身份证号码");
            }
            if (StringUtils.isEmpty(realNameInfo.getNetFrontUrl())) {
                return AjaxResult.error("请填写身份证正面地址");
            }
            if (StringUtils.isEmpty(realNameInfo.getNetBackUrl())) {
                return AjaxResult.error("请填写身份证反面地址");
            }
            if (StringUtils.isEmpty(realNameInfo.getMobile())) {
                return AjaxResult.error("请填写手机号");
            }
            // 经营地址的判断
            if (StringUtils.isEmpty(realNameInfo.getProvince()) || StringUtils.isEmpty(realNameInfo.getCity()) || StringUtils.isEmpty(realNameInfo.getDistrict()) || StringUtils.isEmpty(realNameInfo.getAddress())) {
                return AjaxResult.error("请填写经营地址");
            }
            // 开户行和银行卡号
            if (StringUtils.isEmpty(realNameInfo.getBankCode()) || StringUtils.isEmpty(realNameInfo.getBankCardNo())) {
                return AjaxResult.error("请填写开户行和银行卡号");
            }
        }

        MicroMerchantInfo microMerchantInfo = new MicroMerchantInfo();
        microMerchantInfo.setMchTransparentNo("MCH_" + IdUtil.simpleUUID());
        microMerchantInfo.setNotifyUrl(domainurl+"/kcsm/merchant/notify");
        microMerchantInfo.setBusinessRole("SETTLED_MERCHANT");
        microMerchantInfo.setParentMerchantNo("10091478670");
        // 商户主题信息
        microMerchantInfo.setSignName(realNameInfo.getSignName());
        microMerchantInfo.setShortName(realNameInfo.getShortName());
        // 商户法人信息
        microMerchantInfo.setLegalLicenceType("ID_CARD");
        microMerchantInfo.setLegalLicenceNo(realNameInfo.getLegalLicenceNo());
        microMerchantInfo.setLegalLicenceFrontUrl(realNameInfo.getNetFrontUrl());
        microMerchantInfo.setLegalLicenceBackUrl(realNameInfo.getNetBackUrl());
        microMerchantInfo.setLegalMobile(realNameInfo.getMobile());
        // 经营地址
        microMerchantInfo.setProvince(realNameInfo.getProvince());
        microMerchantInfo.setCity(realNameInfo.getCity());
        microMerchantInfo.setDistrict(realNameInfo.getDistrict());
        microMerchantInfo.setAddress(realNameInfo.getAddress());
        // 开通产品信息 json
        JSONArray productList = new JSONArray();
        JSONObject productInfo = new JSONObject();
        productInfo.put("productCode", "D1");
        productInfo.put("rateType", "SINGLE_FIXED");
        productInfo.put("fixedRate", "0");
        JSONObject settlementProduct = new JSONObject();
        settlementProduct.put("productCode", "ENTERPRISE_WITHDRAW_STANDARD_REALTIME"); // 结算产品代码，需要根据实际接口文档确认
        settlementProduct.put("rateType", "SINGLE_FIXED");
        settlementProduct.put("fixedRate", "1");
        productList.add(productInfo);
        productList.add(settlementProduct);
        microMerchantInfo.setProductInfo(productList.toJSONString());
        // 结算账户信息
        JSONObject accountInfo = new JSONObject();
        accountInfo.put("bankAccountType", "DEBIT_CARD");
        accountInfo.put("bankCardNo", realNameInfo.getBankCardNo());
        accountInfo.put("bankCode", realNameInfo.getBankCode());
        accountInfo.put("settlementDirection", "ACCOUNT");
        microMerchantInfo.setAccountInfo(accountInfo.toJSONString());

        JSONObject res = this.registerMicroMerchant(microMerchantInfo);
        String returnCode = res.getString("returnCode");
        String requestNo = res.getString("requestNo");
        String applicationNo = res.getString("applicationNo");
        String applicationStatus = res.getString("applicationStatus");
        String merchantNo = res.getString("merchantNo");
        String transparentId = res.getString("transparentId");
        String returnMsg = res.getString("returnMsg");

        // 更新realNameInfo信息
        realNameInfo.setRequestNo(requestNo);
        realNameInfo.setApplicationNo(applicationNo);
        realNameInfo.setApplicationStatus(applicationStatus);
        realNameInfo.setMerchantNo(merchantNo);
        realNameInfo.setTransparentId(transparentId);
        realNameInfo.setReturnMsg(returnMsg);
        realNameInfo.setRemark("returnCode:" + returnCode + ";" + "returnMsg:" + returnMsg);
        // 注意：这里需要注入service来更新数据库，暂时注释掉
         realNameInfoService.updateById(realNameInfo);
        return AjaxResult.success(returnMsg);
    }
    /**
     * 特约商户入网(小微)
     *
     * @param merchantInfo 商户信息
     * @return 入网结果
     */
    public JSONObject registerMicroMerchant(@RequestBody MicroMerchantInfo merchantInfo) {
        try {
            // 配置支付参数（根据实际环境配置）
            Xunpay.mchNo = "M1752112514"; // 商户号
            Xunpay.appId = "686f1d82e4b02e1c8b4b5935"; // 应用ID
            //秘钥
            Xunpay.apiKey = "fPqfOo0sVJ31uvWZPH3iRvnNIkJDeW0bajMWaU7lJPvXNlA2RgI4E3TA68qstVd1YXeMYqH8zTra460UItPDcVZ8Kk6iPR1AgvpBQCSqIOa9rCsGeQ1vHi35jWXRPeTe";

            XunpayClient xunpayClient = new XunpayClient();
            ChannelTransparentRequest request = new ChannelTransparentRequest();
            ChannelTransparentReqModel model = new ChannelTransparentReqModel();

            // 设置基础参数
            model.setMchNo(Xunpay.mchNo);
            model.setAppId(Xunpay.appId);
            model.setCtCode("yeepay_JJ003"); // 固定值(小微商户)
            model.setMchTransparentNo("MCH_" + IdUtil.simpleUUID()); // 商户生成的订单号
            model.setNotifyUrl(merchantInfo.getNotifyUrl());

            // 构建params参数
            Map<String, String> params = new HashMap<>();

            // 必填参数
            params.put("businessRole", merchantInfo.getBusinessRole());
            params.put("parentMerchantNo", merchantInfo.getParentMerchantNo());

            // 商户主体信息
            JSONObject merchantSubjectInfo = new JSONObject();
            merchantSubjectInfo.put("signName", merchantInfo.getSignName());
            merchantSubjectInfo.put("shortName", merchantInfo.getShortName());
            params.put("merchantSubjectInfo", merchantSubjectInfo.toJSONString());

            // 商户法人信息
            JSONObject merchantCorporationInfo = new JSONObject();
            merchantCorporationInfo.put("legalLicenceType", merchantInfo.getLegalLicenceType());
            merchantCorporationInfo.put("legalLicenceNo", merchantInfo.getLegalLicenceNo());
            merchantCorporationInfo.put("legalLicenceFrontUrl", merchantInfo.getLegalLicenceFrontUrl());
            merchantCorporationInfo.put("legalLicenceBackUrl", merchantInfo.getLegalLicenceBackUrl());
            merchantCorporationInfo.put("mobile", merchantInfo.getLegalMobile());
            params.put("merchantCorporationInfo", merchantCorporationInfo.toJSONString());

            // 经营地址
            JSONObject businessAddressInfo = new JSONObject();
            businessAddressInfo.put("province", merchantInfo.getProvince());
            businessAddressInfo.put("city", merchantInfo.getCity());
            businessAddressInfo.put("district", merchantInfo.getDistrict());
            businessAddressInfo.put("address", merchantInfo.getAddress());
            params.put("businessAddressInfo", businessAddressInfo.toJSONString());

            // 结算账户信息
            params.put("accountInfo", merchantInfo.getAccountInfo());

            // 开通产品信息
            params.put("productInfo", merchantInfo.getProductInfo());

            // 可选参数
            if (merchantInfo.getIndustryCategoryInfo() != null) {
                params.put("industryCategoryInfo", merchantInfo.getIndustryCategoryInfo());
            }

            // 将params转为JSON字符串
            model.setParams(JSON.toJSONString(params));
            request.setBizModel(model);

            // 发起请求
            ChannelTransparentResponse response = (ChannelTransparentResponse) xunpayClient.execute(request);

            // 处理响应结果
            if (response.isSuccess(Xunpay.apiKey)) {
                // 解析res字段获取详细信息
                JSONObject data = JSON.parseObject(JSON.toJSONString(response.getData()));
                String resStr = data.getString("res");
                JSONObject res = JSON.parseObject(resStr);

                JSONObject result = new JSONObject();
                result.put("returnCode", res.getString("returnCode"));
                result.put("returnMsg", res.getString("returnMsg"));
                result.put("requestNo", res.getString("requestNo"));
                result.put("applicationNo", res.getString("applicationNo"));
                result.put("applicationStatus", res.getString("applicationStatus"));
                result.put("merchantNo", res.getString("merchantNo"));
                return result;
            } else {
                JSONObject errorResult = new JSONObject();
                errorResult.put("returnCode", "FAIL");
                errorResult.put("returnMsg", "请求失败");
                return errorResult;
            }
        } catch (XunpayException e) {
            JSONObject errorResult = new JSONObject();
            errorResult.put("returnCode", "ERROR");
            errorResult.put("returnMsg", "系统异常: " + e.getMessage());
            return errorResult;
        } catch (Exception e) {
            JSONObject errorResult = new JSONObject();
            errorResult.put("returnCode", "ERROR");
            errorResult.put("returnMsg", "系统异常: " + e.getMessage());
            return errorResult;
        }
    }


    public static void main(String[] args) {
        // 创建测试用的小微商户信息
        MicroMerchantController controller = new MicroMerchantController();
        MicroMerchantInfo merchantInfo = new MicroMerchantInfo();

        // 设置基础参数
        merchantInfo.setMchTransparentNo("MCH_" + IdUtil.simpleUUID());
        merchantInfo.setNotifyUrl("http://your-domain.com/merchant/micro/notify");

        // 设置必填参数
        merchantInfo.setBusinessRole("SETTLED_MERCHANT");
        merchantInfo.setParentMerchantNo("10091478670");

        // 设置商户主体信息
        merchantInfo.setSignName("张三小吃店");
        merchantInfo.setShortName("张三小吃");

        // 设置商户法人信息
        merchantInfo.setLegalLicenceType("ID_CARD");
        merchantInfo.setLegalLicenceNo("130123199001011234");
        merchantInfo.setLegalLicenceFrontUrl("http://staticres.yeepay.com/jcptb-merchant-netinjt05/2025/07/31/merchant-1753925985924-b4d87bf1-19d8-47d8-821e-f2975b6a5084-FnEkuHaBDzRrbNiSLRKe.jpg");
        merchantInfo.setLegalLicenceBackUrl("http://staticres.yeepay.com/jcptb-merchant-netinjt05/2025/07/31/merchant-1753925988177-c3050f46-94f6-4600-9b0c-e002f22fcbac-zMACEcmSecUJKXTREVgW.jpg");
        merchantInfo.setLegalMobile("13800138000");

        // 设置经营地址
        merchantInfo.setProvince("110000");
        merchantInfo.setCity("110100");
        merchantInfo.setDistrict("110101");
        merchantInfo.setAddress("北京市东城区王府井大街1号");

        // 设置开通产品信息
        JSONArray productInfoArray = new JSONArray();
        JSONObject product1 = new JSONObject();
        product1.put("productCode", "MERCHANT_SCAN_ALIPAY_OFFLINE");
        product1.put("rateType", "SINGLE_PERCENT");
        product1.put("percentRate", "0.3");
        productInfoArray.add(product1);

        JSONObject product2 = new JSONObject();
        product2.put("productCode", "MERCHANT_SCAN_WECHAT_OFFLINE");
        product2.put("rateType", "SINGLE_PERCENT");
        product2.put("percentRate", "0.3");
        productInfoArray.add(product2);

        merchantInfo.setProductInfo(productInfoArray.toJSONString());

        // 设置结算账户信息
        JSONObject accountInfo = new JSONObject();
        accountInfo.put("bankAccountType", "DEBIT_CARD");
        accountInfo.put("bankCardNo", "6222001234567890123");
        accountInfo.put("bankCode", "ICBC");
        merchantInfo.setAccountInfo(accountInfo.toJSONString());

        // 调用注册方法
        JSONObject result = controller.registerMicroMerchant(merchantInfo);
        System.out.println("注册结果: " + result.toJSONString());
    }

    /**
     * 商户入网结果通知回调接口
     *
     * @param notifyData 通知数据
     * @return 处理结果
     */
    @PostMapping("/notify")
    public Object merchantNotify(@RequestBody JSONObject notifyData) {
        try {
            // 处理通知数据
            String transparentId = notifyData.getString("transparentId");
            String res = notifyData.getString("res");
            String appId = notifyData.getString("appId");
            String sign = notifyData.getString("sign");

            // 解析res字段获取详细信息

            // 解码res
            String decodedRes = URLDecoder.decode(res, StandardCharsets.UTF_8);
            System.out.println("Decoded Res: " + decodedRes);
            JSONObject jsonObject = JSONObject.parseObject(decodedRes);
            // 直接解析 decodedRes，它已经是一个合法的JSON字符串
            System.out.println("Parsed JSON Object: " + jsonObject.toJSONString());

            String requestNo = jsonObject.getString("requestNo");
            String applicationNo = jsonObject.getString("applicationNo");
            String applicationStatus = jsonObject.getString("applicationStatus");
            String merchantNo = jsonObject.getString("merchantNo");
            if(com.party.common.utils.StringUtils.isNotEmpty(requestNo)){
                QueryWrapper<RealNameInfo> realNameInfoQueryWrapper = new QueryWrapper<>();
                realNameInfoQueryWrapper.eq("request_no",requestNo);
                List<RealNameInfo> list = realNameInfoService.list(realNameInfoQueryWrapper);
                if(list.size()>0){
                    RealNameInfo realNameInfo = list.get(0);
                    // 如果不是已完成状态
                    if(!"COMPLETED".equals(realNameInfo.getApplicationStatus())){
                        realNameInfo.setApplicationStatus(jsonObject.getString("applicationStatus"));
                        realNameInfo.setAgreementSignUrl(jsonObject.getString("agreementSignUrl"));
                        realNameInfo.setRequestNo(jsonObject.getString("requestNo"));
                        realNameInfo.setMerchantNo(jsonObject.getString("merchantNo"));
                        realNameInfo.setRemark(jsonObject.toJSONString());
                        realNameInfo.setTransparentId(transparentId);
                        realNameInfoService.updateById(realNameInfo);
                    }

                }

            }
            // 记录日志或更新数据库状态
            System.out.println("收到小微商户入网通知:");
            System.out.println("transparentId: " + transparentId);
            System.out.println("requestNo: " + requestNo);
            System.out.println("applicationNo: " + applicationNo);
            System.out.println("applicationStatus: " + applicationStatus);
            System.out.println("merchantNo: " + merchantNo);

            // 返回成功响应
            JSONObject result = new JSONObject();
            result.put("code", "SUCCESS");
            result.put("message", "处理成功");
            return result;
        } catch (Exception e) {
            JSONObject result = new JSONObject();
            result.put("code", "FAIL");
            result.put("message", "处理失败: " + e.getMessage());
            return result;
        }
    }
}
